package com.springboot.testspringboot.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import android.widget.Toast;

import androidx.annotation.NonNull;


public class ToastUtils {

    private static Context mContext;
    private static final int TOAST_MSG = 999;
    private static Toast toast;
    private static Handler mMainHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TOAST_MSG:
                    toast = Toast.makeText(mContext, (String) msg.obj, Toast.LENGTH_SHORT);
                    if (toast != null) {
                        toast.show();
                    }

                    break;
                default:
                    break;
            }

        }
    };

    public static void showInMainThread(Context context, String str) {
        toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
        if (toast != null) {
            toast.show();
        }

    }

    public static void showInThread(Context context, String str) {
        mContext = context;
        if (mMainHandler != null) {
            mMainHandler.sendMessage(mMainHandler.obtainMessage(TOAST_MSG, str));
        }
    }

    public static void showDelayed(Context context, String str) {
        mContext = context;
        if (mMainHandler != null) {
            mMainHandler.sendMessageDelayed(mMainHandler.obtainMessage(TOAST_MSG, str), 800);
        }
    }


    public static void destory() {
        if (mMainHandler != null) {
            mMainHandler.removeMessages(TOAST_MSG);
            mMainHandler = null;
        }
        if (toast != null) {
            toast.cancel();
            toast = null;
        }
    }
}
